package com.uzai.console.service.vph.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.uzai.common.enums.OrderReStatusEnum;
import com.uzai.common.enums.OrderStatusEnum;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.feign.vphorder.VphOrderPullDto;
import com.uzai.console.dto.feign.vphorder.VphOrderSettledDto;
import com.uzai.console.dto.vph.vphorder.VphFindUnReceicedDto;
import com.uzai.console.dto.vph.vphorder.VphOrderDownLoadDto;
import com.uzai.console.entity.VphOrder;
import com.uzai.console.entity.VphToken;
import com.uzai.console.mapper.VphOrderMapper;
import com.uzai.console.mapper.VphTokenMapper;
import com.uzai.console.para.VphOrderRemoteApiPara;
import com.uzai.console.service.feign.VphOrderFeignService;
import com.uzai.console.service.remoteapi.VphOrderRemoteApiService;
import com.uzai.console.service.vph.VphOrderSyncService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: liuqi
 * @Date: 2019/11/27 11:23
 * @Description:
 */
@Service
public class VphOrderSyncServiceImpl implements VphOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(VphOrderSyncServiceImpl.class);

    @Autowired
    private VphTokenMapper vphTokenMapper;
    @Autowired
    private VphOrderMapper vphOrderMapper;
    @Autowired
    private VphOrderRemoteApiService vphOrderRemoteApiService;
    @Autowired
    private VphOrderFeignService vphOrderFeignService;


    /**
     * 手动下载单个京东联盟订单
     *
     * @param vphOrderDownLoadDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void downloadOrder(VphOrderDownLoadDto vphOrderDownLoadDto, Long vphTokenId) {

        //调用订单业务库服务器
        VphToken vphToken = vphTokenMapper.selectById(vphTokenId, vphOrderDownLoadDto.getMerId());
        if (vphToken != null) {
            try {
                VphOrderPullDto vphOrderPullDto = new VphOrderPullDto();
                vphOrderPullDto.setTokenId(vphToken.getOpenId());
                vphOrderPullDto.setPlatform("vph");
                vphOrderPullDto.setStartTime(vphOrderDownLoadDto.getQueryStartTime());
                vphOrderPullDto.setEndTime(vphOrderDownLoadDto.getQueryEndTime());
                vphOrderPullDto.setTimeType(vphOrderDownLoadDto.getQueryTimeType());
                //请求订单拉取接口
                vphOrderFeignService.pull(vphOrderPullDto);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }

        if (vphToken != null) {
            //调用订单拉取库服务器
            VphOrderRemoteApiPara vphOrderRemoteApiPara = new VphOrderRemoteApiPara();
            vphOrderRemoteApiPara.setAccessToken(vphToken.getAccessToken());
            vphOrderRemoteApiPara.setOpenId(vphToken.getOpenId());
            vphOrderRemoteApiPara.setQueryTimeType(vphOrderDownLoadDto.getQueryTimeType());
            vphOrderRemoteApiPara.setQueryStartTime(vphOrderDownLoadDto.getQueryStartTime());
            vphOrderRemoteApiPara.setQueryEndTime(vphOrderDownLoadDto.getQueryEndTime());
            vphOrderRemoteApiService.remoteDownload(vphOrderRemoteApiPara);
            try {
                Thread.sleep(100); //线程停顿0.1秒先刷新正常订单，在刷新维权订单
            } catch (Exception e) {

            }

            //调用维权订单拉取库服务器
            VphOrderRemoteApiPara vphOrderRemoteApiPara_refund = new VphOrderRemoteApiPara();
            vphOrderRemoteApiPara_refund.setAccessToken(vphToken.getAccessToken());
            vphOrderRemoteApiPara_refund.setOpenId(vphToken.getOpenId());
            vphOrderRemoteApiPara_refund.setQueryTimeType(vphOrderDownLoadDto.getQueryTimeType());
            vphOrderRemoteApiPara_refund.setQueryStartTime(vphOrderDownLoadDto.getQueryStartTime());
            vphOrderRemoteApiPara_refund.setQueryEndTime(vphOrderDownLoadDto.getQueryEndTime());
            vphOrderRemoteApiService.remoteDownloadRefund(vphOrderRemoteApiPara_refund);
        }
    }

    /**
     * 异步手动下载多个京东联盟订单
     *
     * @param vphOrderDownLoadDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Async("taskExecutor")
    @Override
    public void downloadOrderListSync(VphOrderDownLoadDto vphOrderDownLoadDto) {
        if (vphOrderDownLoadDto.getIdList() != null && vphOrderDownLoadDto.getIdList().size() > 0) {
            for (Long id : vphOrderDownLoadDto.getIdList()) {
                try {
                    downloadOrder(vphOrderDownLoadDto, id);
                } catch (Exception e) {
                    logger.error("-------downloadOrderListSync is error vphTokenId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 远程调用订单库API，手动更新单个订单
     *
     * @param vphOrder
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Async("taskExecutor")
    @Override
    public void updateVphOrder(VphOrder vphOrder) {

        if (vphOrder == null) {
            return;
        }

        VphOrderRemoteApiPara vphOrderRemoteApiPara = new VphOrderRemoteApiPara();
        if (StringUtils.isNotBlank(vphOrder.getOpenid())) {
            VphToken vphToken = vphTokenMapper.selectByOpenId(vphOrder.getOpenid());
            if (vphToken != null) {
                vphOrderRemoteApiPara.setAccessToken(vphToken.getAccessToken());
                vphOrderRemoteApiPara.setQueryTimeType(1); //创建时间
                vphOrderRemoteApiPara.setQueryStartTime(vphOrder.getCreatedt() - 1);
                vphOrderRemoteApiPara.setQueryEndTime(vphOrder.getCreatedt() + 1);
                vphOrderRemoteApiPara.setChildOrderNo(vphOrder.getChildOrderNo());
                vphOrderRemoteApiService.remoteDownload(vphOrderRemoteApiPara);
            }
        }
    }

    /**
     * 远程调用订单库API，更新7天前未收货订单
     *
     * @param merId
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Async("taskExecutor")
    @Override
    public void updateVphOrderUnReceivedListSync(Long merId) {

        //查询7天前未收货订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        //设置开始时间为90天前
        Integer now = DateUtil.getNowTime();
        vphFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为7天前
        vphFindUnReceicedDto.setQueryEndTime(now - 604800);
        //查询付款状态订单（未收货）
        vphFindUnReceicedDto.setStatus(0);

        List<VphOrder> vphOrderList = vphOrderMapper.findUnReceivedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    updateVphOrder(vphOrder);
                } catch (Exception e) {
                    logger.error("-------updateVphOrderUnReceivedList is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    @Override
    public void uploadVphOrderSettingSync(Long merId, int day, int status, List<Integer> sourceStatus) {
        if (merId == null) {
            return;
        }
        //设置结束时间为day天前
        int endTime = DateUtil.getNowTime() - day * 24 * 3600;
        vphOrderMapper.updateStatusPayCompleteToSettle(null, endTime, null, merId, status, sourceStatus);
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     *
     * @param merId
     * @param day
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateVphOrderUnReceivedListSync(Long merId, int day) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        vphFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        vphFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（未收货）
        vphFindUnReceicedDto.setStatus(0);
        List<VphOrder> vphOrderList = vphOrderMapper.findUnReceivedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    updateVphOrder(vphOrder);
                } catch (Exception e) {
                    logger.error("-------updateVphOrderUnReceivedListSync is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前已冻结的订单
     *
     * @param merId
     * @param day
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateVphOrderFreezedListSync(Long merId, int day) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        vphFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        vphFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（已收货）
        vphFindUnReceicedDto.setStatus(1);
        List<VphOrder> vphOrderList = vphOrderMapper.findFreezedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    updateVphOrder(vphOrder);
                } catch (Exception e) {
                    logger.error("-------updateVphOrderFreezedListSync is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateVphOrderUnReceivedListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        vphFindUnReceicedDto.setQueryStartTime(startTime);
        vphFindUnReceicedDto.setQueryEndTime(endTime);
        vphFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        vphFindUnReceicedDto.setStatus(0);
        List<VphOrder> vphOrderList = vphOrderMapper.findUnReceivedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    updateVphOrder(vphOrder);
                } catch (Exception e) {
                    logger.error("-------updateVphOrderUnReceivedListSync is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 直接结算，更新day天前未收货订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateVphOrderUnReceivedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        vphFindUnReceicedDto.setQueryStartTime(startTime);
        vphFindUnReceicedDto.setQueryEndTime(endTime);
        vphFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        vphFindUnReceicedDto.setStatus(0);
        List<VphOrder> vphOrderList = vphOrderMapper.findUnReceivedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    //订单状态为0-付款状态时，才能确认收货
                    if (vphOrder.getStatus() == 0) {
                        //调用确认收货接口
                        VphOrderSettledDto vphOrderSettledDto = new VphOrderSettledDto();
                        vphOrderSettledDto.setMerId(vphOrder.getMerId());
                        vphOrderSettledDto.setOrderId(vphOrder.getParentOrderNo());
                        vphOrderSettledDto.setChildOrderId(vphOrder.getChildOrderNo());
                        vphOrderSettledDto.setItemId(vphOrder.getItemId());
                        vphOrderSettledDto.setSizeId(vphOrder.getSizeId());
                        UzaiRespVo<Object> result = vphOrderFeignService.settled(vphOrderSettledDto);
                        logger.info("---唯品会订单确认收货---dto={}, result={}", JSONObject.toJSONString(vphOrderSettledDto), JSONObject.toJSONString(result));
                    }
                } catch (Exception e) {
                    logger.error("-------updateVphOrderUnReceivedListSync_settle is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前已冻结的订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateVphOrderFreezedListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        vphFindUnReceicedDto.setQueryStartTime(startTime);
        vphFindUnReceicedDto.setQueryEndTime(endTime);
        vphFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        vphFindUnReceicedDto.setStatus(1);
        List<VphOrder> vphOrderList = vphOrderMapper.findFreezedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    updateVphOrder(vphOrder);
                } catch (Exception e) {
                    logger.error("-------updateVphOrderFreezedListSync is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 直接结算，更新day天前已冻结订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateVphOrderFreezedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        vphFindUnReceicedDto.setQueryStartTime(startTime);
        vphFindUnReceicedDto.setQueryEndTime(endTime);
        vphFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        vphFindUnReceicedDto.setStatus(1);
        List<VphOrder> vphOrderList = vphOrderMapper.findFreezedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    //先将订单状态为0-付款状态时，才能确认收货
                    vphOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    vphOrder.setUpdateTime(DateUtil.getNowTime());
                    vphOrderMapper.updateStatus(vphOrder);
                    //调用确认收货接口
                    VphOrderSettledDto vphOrderSettledDto = new VphOrderSettledDto();
                    vphOrderSettledDto.setMerId(vphOrder.getMerId());
                    vphOrderSettledDto.setOrderId(vphOrder.getParentOrderNo());
                    vphOrderSettledDto.setChildOrderId(vphOrder.getChildOrderNo());
                    vphOrderSettledDto.setItemId(vphOrder.getItemId());
                    vphOrderSettledDto.setSizeId(vphOrder.getSizeId());
                    UzaiRespVo<Object> result = vphOrderFeignService.settled(vphOrderSettledDto);
                    logger.info("---唯品会订单确认收货---dto={}, result={}", JSONObject.toJSONString(vphOrderSettledDto), JSONObject.toJSONString(result));
                } catch (Exception e) {
                    logger.error("-------updateVphOrderFreezedListSync_settle is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前维权中订单
     *
     * @param merId
     * @param day
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateVphOrderRefundingListSync(Long merId, int day) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        vphFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        vphFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（未收货）
        vphFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<VphOrder> vphOrderList = vphOrderMapper.findUnReceivedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    updateVphOrder(vphOrder);
                } catch (Exception e) {
                    logger.error("-------updateVphOrderRefundingListSync is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前维权中订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateVphOrderRefundingListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前维权中订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        vphFindUnReceicedDto.setQueryStartTime(startTime);
        vphFindUnReceicedDto.setQueryEndTime(endTime);
        vphFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        vphFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<VphOrder> vphOrderList = vphOrderMapper.findUnReceivedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    updateVphOrder(vphOrder);
                } catch (Exception e) {
                    logger.error("-------updateVphOrderRefundingListSync is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 直接结算，更新day天前维权中订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateVphOrderRefundingListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        VphFindUnReceicedDto vphFindUnReceicedDto = new VphFindUnReceicedDto();
        vphFindUnReceicedDto.setMerId(merId);
        vphFindUnReceicedDto.setQueryStartTime(startTime);
        vphFindUnReceicedDto.setQueryEndTime(endTime);
        vphFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        vphFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        //根据订单返利状态查询
        vphFindUnReceicedDto.setReStatusList(Lists.newArrayList(OrderReStatusEnum.RE_STATUS_NO_VALUE, OrderReStatusEnum.RE_STATUS_FROZEN_VALUE));
        List<VphOrder> vphOrderList = vphOrderMapper.findUnReceivedList(vphFindUnReceicedDto);
        if (vphOrderList != null) {
            for (VphOrder vphOrder : vphOrderList) {
                try {
                    //先将订单状态为0-付款状态时，才能确认收货
                    vphOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    vphOrder.setUpdateTime(DateUtil.getNowTime());
                    vphOrderMapper.updateStatus(vphOrder);

                    //调用确认收货接口
                    VphOrderSettledDto vphOrderSettledDto = new VphOrderSettledDto();
                    vphOrderSettledDto.setMerId(vphOrder.getMerId());
                    vphOrderSettledDto.setOrderId(vphOrder.getParentOrderNo());
                    vphOrderSettledDto.setChildOrderId(vphOrder.getChildOrderNo());
                    vphOrderSettledDto.setItemId(vphOrder.getItemId());
                    vphOrderSettledDto.setSizeId(vphOrder.getSizeId());
                    UzaiRespVo<Object> result = vphOrderFeignService.settled(vphOrderSettledDto);
                    logger.info("---唯品会订单确认收货---dto={}, result={}", JSONObject.toJSONString(vphOrderSettledDto), JSONObject.toJSONString(result));
                } catch (Exception e) {
                    logger.error("-------updateVphOrderRefundingListSync_settle is error ordersn={}, error={}", vphOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }
}
